package day19;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectPrc {
    @Test
    public void getClass1() throws ClassNotFoundException {
        Class<?> s1 = Class.forName("day19.Student");
        Class<?> s2 = Student.class;
        Class<?> s3 = new Student().getClass();
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
    /**获取类对象*/
    @Test
    public void getClass3(){
        Class<?> s1 = Student.class;
        System.out.println(s1);
        System.out.println(s1.getName());
        System.out.println(s1.getSimpleName());
        System.out.println(s1.getPackage().getName());
    }

    /**获取构造函数*/
    @Test
    public void getCons(){
        Class<?> s1 = Student.class;
        Constructor<?>[] cs = s1.getConstructors();
        for (Constructor c:cs){
//            System.out.println(c);
            System.out.println(c.getName());
            System.out.println(Arrays.toString(c.getParameterTypes()));
        }
    }
    /**获取普通方法*/
    @Test
    public void getMs(){
        Class<?> s1 = Student.class;
        Method[] methods = s1.getMethods();
//        System.out.println(Arrays.toString(methods));
        for (Method m:methods){
            System.out.print(m.getName()+",");
            System.out.println(Arrays.toString(m.getParameterTypes()));
        }
    }
    /**获取成员变量Fields*/
    @Test
    public void getFs() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<?> s1 = Class.forName("day19.Student");
        Field[] fields = s1.getDeclaredFields();
        for (Field f:fields){
            System.out.print(f.getClass()+",");
            System.out.print(f.getName()+",");
            System.out.println(f.getType());
        }
        Field f = s1.getField("name");
        Object obj = s1.newInstance();
        f.set(obj,"东京老王");
        System.out.println(f.get(obj));
    }
    /**创建实例*/
    @Test
    public void NewIns() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> s1=Student.class;
        Object SCons1 = s1.newInstance();
        System.out.println(SCons1);
        Constructor<?> SCons2 = s1.getConstructor(String.class, int.class);
        Object student1 = SCons2.newInstance("王二", 33);
        System.out.println(student1);
        System.out.println(student1.getClass());
        Student S1=(Student) student1;
        /**使用多态方式实例化student对象,需要将父类对象强制转换成子类对象才可以使用子类属性与方法*/
        System.out.println(S1.age);
        System.out.println(S1.name);
        S1.study();
    }
}
